import 'dart:async';

import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/model/course_resource.dart';

class CourseTimer extends StatefulWidget {
  final CourseResource resource;
  final Function complete;
  final int finishRate;

  CourseTimer({
    Key key,
    @required this.resource,
    @required this.complete,
    @required this.finishRate,
  }) : super(key: key);

  @override
  _CourseTimerState createState() => _CourseTimerState();
}

class _CourseTimerState extends State<CourseTimer> {
  Timer timer;
  int seconds;

  @override
  void initState() {
    super.initState();

    seconds = widget.resource.courseTime - widget.resource.learnTime;
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      setState(() {
        seconds--;
        widget.resource.learnTime++;
      });

      if (widget.resource.learnTime >= widget.resource.courseTime) {
        timer.cancel();
        if (widget.complete != null) {
          widget.complete();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    int min = (seconds / 60).floor();
    int sec = seconds % 60;

    String minStr = min > 9 ? min.toString() : '0$min';
    String secStr = sec > 9 ? sec.toString() : '0$sec';
    if (min == 0) minStr = '0';
    if (sec == 0) secStr = '0';

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 3),
      decoration: BoxDecoration(
        color: Color.fromRGBO(0, 0, 0, 0.5),
      ),
      alignment: Alignment.center,
      child: Text(
        '$minStr分$secStr秒',
        style: TextStyle(
          fontSize: 12,
          color: Colors.white,
        ),
      ),
    );
  }
}
